/*
 * @Description: 
 * @Autor: 商晓彬
 * @Date: 2021-09-02 11:20:05
 * @LastEditors: 商晓彬
 * @LastEditTime: 2021-12-17 09:49:40
 */
import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { MessageService } from '@abp/message/message.service';
import {
    StorePutModelContentDto, StoreFunctionsServiceProxy, StorePutServiceProxy, StoreInfoServiceProxy, ReleaseOrderDto,
    PartsDeliveryServiceProxy,
    NewCertificateOutput,
    AddCertificateInput,
    AlterCertificateInput,
    OthersCancellingInput,
    LabelCollectLong
} from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import * as moment from 'moment';

@Component({
    selector: 'app-add-ex',
    templateUrl: './add-ex.component.html',
    styleUrls: ['./add-ex.component.less']
})
export class AddExComponent extends AppComponentBase {
    //引入子组件
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() warehouseInfo: any;//仓库信息
    @Input() checktype: any
    saving = false;
    active = false;
    releaseOrderOptions = [];
    qualifiedNumberOptions = [];
    selectRow: any = [];// 表格选中行
    queryInfo = new StorePutModelContentDto();
    inputForm = new AddCertificateInput();
    form = new NewCertificateOutput();
    addexTitle: string;
    inventoryPeopleList: LabelCollectLong[];
    operationPerson: any
    operationTime: any = new Date()
    saveFlag = true;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _storeFunctionsServiceProxy: StoreFunctionsServiceProxy,
        private _storePutServiceProxy: StorePutServiceProxy,
        private _storeInfoServiceProxy: StoreInfoServiceProxy,
        private _partsDeliveryServiceProxy: PartsDeliveryServiceProxy,
    ) {
        super(injector);
    }
    resert() {
        this.queryInfo = new StorePutModelContentDto();
    }
    ngOnInit() {
        this.getReleaseOrdersEv()
        this.getQualifiedNumberEv()
        this.getInventoryPeopleListEv()
    }

    //打开弹窗
    onShown(): void {
        this.active = true;
        if (this.checktype && this.checktype == 1) { //查看
            this.addexTitle = '查看出库'
            this.getCertificateByBusinessEv(0)
        } else if (this.checktype && this.checktype == 2) {//修改
            this.addexTitle = '修改出库'
            this.getCertificateByBusinessEv(1)
        } else if (this.checktype && this.checktype == 3) {//退库
            this.addexTitle = '退库作业'
            this.getCertificateByBusinessEv(0)
        } else if (this.checktype && this.checktype == 4) {//退库
            this.addexTitle = '退库查看'
            this.getMsg();
        } else {
            this.addexTitle = '新增出库'
        }
    }
    //出库
    addStoreOutEv() {
        this.inputForm.releaseOrder = this.queryInfo.releaseOrder
        this.inputForm.qualifiedNumber = this.queryInfo.qualifiedNumber
        this.inputForm.outNum = this.selectRow.length
        this.inputForm.storeList = []
        this.selectRow.forEach(element => {
            this.inputForm.storeList.push(element.stockContentId)
        });
        if (this.saveFlag) {
            this.saveFlag = false;
            this._partsDeliveryServiceProxy.addStoreOut(this.inputForm)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this.close()
                        this.modalSave.emit();
                        this._messageService.success("出库成功")
                    } else {
                        this._messageService.error(result.message);
                    }
                });
        }
    }
    // 获取放行单号
    getReleaseOrdersEv() {
        this._partsDeliveryServiceProxy.getReleaseOrders()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.releaseOrderOptions = []
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.releaseOrderOptions.push(data);
                }
            });

    }
    // 合格单号
    getQualifiedNumberEv() {
        this._partsDeliveryServiceProxy.getQualifiedNumber(
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.qualifiedNumberOptions = []
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.qualifiedNumberOptions.push(data);
                }
            });

    }
    getCertificateByNumEv() {
        this.form = new NewCertificateOutput();
        this.selectRow = []
        this.inputForm = new AddCertificateInput()
        this._partsDeliveryServiceProxy.getCertificateByNum(
            this.queryInfo.releaseOrder ? this.queryInfo.releaseOrder : undefined,
            this.queryInfo.qualifiedNumber ? this.queryInfo.qualifiedNumber : undefined,
            0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.form = result
                if (this.form.expirationDate != null) {
                    this.form.expirationDate = moment(this.form.expirationDate).format('YYYY-MM-DD')
                }
                this.selectRow = result.certificateContents.filter(item => {
                    return item.isCheck == true
                })
            });
    }
    // 查看  修改查看
    getCertificateByBusinessEv(type) {
        this.form = new NewCertificateOutput();
        this.selectRow = []
        this.inputForm = new AddCertificateInput()
        this._partsDeliveryServiceProxy.getCertificateByBusiness(
            this.warehouseInfo ? this.warehouseInfo.id : undefined,
            type
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.form = result
                if (this.form.expirationDate != null) {
                    this.form.expirationDate = moment(this.form.expirationDate).format('YYYY-MM-DD')
                }
                this.queryInfo.qualifiedNumber = result.qualifiedNumber
                this.queryInfo.releaseOrder = result.releaseOrder
                this.inputForm.whereAbouts = result.whereAbouts
                this.inputForm.reason = result.remark
                this.selectRow = result.certificateContents.filter(item => {
                    return item.isCheck == true

                })
            });
    }
    getMsg() {
        this.form = new NewCertificateOutput();
        this.selectRow = []
        this.inputForm = new AddCertificateInput()
        this._partsDeliveryServiceProxy.getCancelRecord(
            this.warehouseInfo ? this.warehouseInfo.id : undefined,
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.form = result
                if (this.form.expirationDate != null) {
                    this.form.expirationDate = moment(this.form.expirationDate).format('YYYY-MM-DD')
                }
                this.queryInfo.qualifiedNumber = result.qualifiedNumber
                this.queryInfo.releaseOrder = result.releaseOrder
                this.inputForm.whereAbouts = result.whereAbouts
                this.inputForm.reason = result.remark
                this.selectRow = result.certificateContents.filter(item => {
                    return item.isCheck == true
                })
                this.operationPerson = { label: result.cancellingUser, value: result.cancellingUserId };
                this.operationTime = result.cancellingTime;
            });
    }
    // 保存修改
    alterCertificateByBusinessEv() {
        let info = new AlterCertificateInput()
        info.releaseOrder = this.queryInfo.releaseOrder
        info.qualifiedNumber = this.queryInfo.qualifiedNumber
        info.outNum = this.selectRow.length
        info.storeList = []
        this.selectRow.forEach(element => {
            info.storeList.push(element.stockContentId)
        });
        info.reason = this.inputForm.reason
        info.id = this.warehouseInfo.id
        info.operation = 3;
        if (this.saveFlag) {
            this.saveFlag = false;
            this._partsDeliveryServiceProxy.alterCertificateByBusiness(
                info
            )
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this._messageService.success("修改成功")
                        this.modalSave.emit();
                        this.close()
                    } else {
                        this._messageService.error(result.message);
                    }
                });
        }

    }
    //退库人
    getInventoryPeopleListEv() {
        this._partsDeliveryServiceProxy.getInventoryPeopleList()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.inventoryPeopleList = result
            });
    }
    // 退库
    addCancellingHandleEv() {
        let info = new OthersCancellingInput()
        info.cancellingUser = this.operationPerson.label
        info.cancellingUserId = this.operationPerson.value
        info.storeIdList = []
        this.selectRow.forEach(element => {
            info.storeIdList.push(element.stockContentId)
        });
        info.deliveryDocumentId = this.warehouseInfo.id
        info.cancellingReason = this.inputForm.reason
        if (this.saveFlag) {
            this.saveFlag = false;
            this._partsDeliveryServiceProxy.addCancellingHandle(
                info
            )
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this._messageService.success("退库成功")
                        this.close()
                        this.modalSave.emit();
                    } else {
                        this._messageService.error(result.message);
                    }
                });
        }
    }
    //查看新增任务
    show(): void {
        this.active = true;
        this.modal.show();
    }
    //关闭事件
    close(): void {
        //清空form表单
        this.form = new NewCertificateOutput();
        this.queryInfo = new StorePutModelContentDto();
        this.selectRow = []
        this.inputForm = new AddCertificateInput()
        this.active = false;
        this.modal.hide();
    }
}
